import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

// StatefulWidget 是真正的组件本体，用于接收外部传入的数据
class StatefullCase extends StatefulWidget {
  // 出于性能优化考虑，组件都推荐添加 const 保持组件不可变性
  const StatefullCase({super.key, this.title = '状态管理'});
  // 定义一个属性，用于接收外部传入的数据
  final String title;

  @override
  createState() {
    return _StatefullCaseState();
  }
}

// State 是组件的状态类，单独管理组件的状态、UI 更新、生命周期
class _StatefullCaseState extends State<StatefullCase> {
  int count = 0;
  List channelList = [];

  @override
  void initState() {
    super.initState();
    // 初始化状态
    count = 10;
    // 组件初始化时调用
    getChannelList();
  }

  void getChannelList() async {
    // 1. 创建 Dio 对象
    final dio = Dio();
    final res = await dio.get('https://geek.itheima.net/v1_0/channels');
    setState(() {
      channelList = res.data['data']['channels'];
    });
    print(res.data['data']['channels']);
  }

  @override
  void dispose() {
    super.dispose();
    // 组件销毁时调用
  }

  @override
  Widget build(BuildContext context) {
    // 打印组件的属性
    // print('组件的build函数被调用了');
    return Center(
      child: Column(
        children: [
          // 打印父传子数据
          Text('父传子数据：${widget.title}'),
          ElevatedButton(
            onPressed: () {
              // print('点击+1 --- $count');
              setState(() {
                count++;
              });
            },
            child: Text('点击+1 --- $count'),
          ),
          Text('数据长度:${channelList.length}'),
          Expanded(
            flex: 1,
            child: ListView.builder(
              itemCount: channelList.length,
              itemBuilder: (context, index) {
                return Container(
                  height: 100,
                  margin:
                      const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                  width: double.infinity,
                  color: Colors.green,
                  child: Text(channelList[index]['name']),
                );
              },
            ),
          )
        ],
      ),
    );
  }
}
